package com.itbaizhan.shopping_manager_api.security;

/**
 * @author spf
 * @date 2023/12/16
 * @time 12:18
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * SpringSecurity配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义表单登录
        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/admin/login")
                .successHandler(new MyLoginSuccessHandler())
                .failureHandler(new MyLoginFailureHandler());

        // 权限拦截配置
        http.authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/admin/login").permitAll()
                .anyRequest().authenticated();

        // 退出登录配置
        http.logout()
                .logoutUrl("/admin/logout")
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .clearAuthentication(true)
                .invalidateHttpSession(true);

        // 异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(new MyAuthenticationEntryPoint())
                .accessDeniedHandler(new MyAccessDeniedHandler());

        // 关闭csrf防护
        http.csrf().disable();

        // 开启跨域请求
        http.cors();
    }

    // 密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
